<?php

namespace app\admin\controller\pay;

use app\common\controller\Backend;

/**
 * 支付订单管理
 */
class Pay extends Backend
{
    protected $relationSearch = true;

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Pay.Pay');
        
        $this->view->assign("PayType", $this->model->GetPayType());
        $this->assignconfig('PayType', $this->model->GetPayType());

        $this->view->assign("StatusList", $this->model->GetStatusList());
        $this->assignconfig("StatusList", $this->model->GetStatusList());
    }

    //列表
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) 
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    // 删除
    public function del($ids = null)
    {
        $ids = $ids ?: $this->request->param('ids',0,'trim');

        $list = $this->model->select($ids);

        if(!$list)
        {
            $this->error('请选择需要删除订单');
        }

        $result = $this->model->destroy($ids);

        if($result === false)
        {
            $this->error('删除失败');
        }else{
            $this->success('删除成功');
        }

    }

    //补单
    public function repair($ids = null)
    {
        $pay = $this->model->find($ids);

        if(!$pay)
        {
            $this->error('需要补单的订单不存在');
            exit;
        }

        //发送回调通知
        $result = HttpRequest($pay['notice'], $pay->toArray());

        if($result === false)
        {
            $this->error('补单异常');
            exit;
        }

        $res = json_decode($result,true);

        $code = isset($res['code']) ? trim($res['code']) : 0;

        if($code === 0)
        {
            $this->error('补单失败');
            exit;
        }else
        {
            $PayData = [
                'id' => $ids,
                'status' => 1,
            ];

            $result = $this->model->isUpdate(true)->save($PayData);

            if($result === false)
            {
                $this->error('补单失败');
                exit;
            }else
            {
                $this->success('补单成功');
                exit;
            }
        }
    }

}